#! /usr/bin env python3
# -*- coding:utf-8 -*-
"""
作者： kratos
时间： 2020年08月28日 22:03
用途：集成工具为App使用
"""
import datetime
import os
import sys
import markdown
from WebApi import settings

loglevel = {
    "debug": 0,
    "info": 1,
    "warn": 2,
    "error": 3
}

work_dir = settings.BASE_DIR
resouce_dir = os.path.join(work_dir, "Res")
config_dir = os.path.join(work_dir, "Config")
cache_dir = os.path.join(work_dir, "cache")
config_file_name = os.path.join(config_dir, "user.conf")
templeates_dir = os.path.join(work_dir, "templates")


def init_all_resouce():
    config_dict = {}
    with open(os.path.join(work_dir, config_file_name), 'r', encoding='utf-8') as config_file:
        all_config = config_file.read()
    config_list_tmp = all_config.split("[")

    for config_data in config_list_tmp:
        if config_data:
            config_list = config_data.split("]", maxsplit=1)
            config_dict[config_list[0]] = {}
            for key_value in config_list[1].split("\n"):
                if key_value and not key_value[0] == "#":
                    key, value = key_value.split("=", maxsplit=1)
                    config_dict[config_list[0]][key] = value
    return config_dict


all_config = init_all_resouce()


# 用途：记录日志，分debug、info、warn、error四个等级
def loger(msg: str, logfrom=os.path.basename(sys.argv[0]).replace(".py", ""), level="info"):
    now = datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')
    logstr = "[%s] [%s] %s\n" % (level, now, msg)

    if loglevel[level] > loglevel[all_config["log"]["level"]]:
        path = os.path.join(work_dir, all_config["log"]["logdir"])
        if not os.path.exists(path):
            os.makedirs(path.encode('utf-8'))
        with open(os.path.join(path, logfrom + ".log"), 'a', encoding='utf-8') as log_file:
            log_file.write(logstr)
    print(logstr, end="")


# 将文本转成html
def str2html(rel_str: str, str_type: str, filename="", path=""):
    if str_type == "markdown":
        html_str = markdown.markdown(rel_str)
    elif str_type == "text":
        html_str = "<pre>%s</pre>" % rel_str
    else:
        return False
    if filename and path:
        if not os.path.exists(path):
            os.makedirs(path.encode('utf-8'))
        with open(os.path.join(path, filename + ".html"), 'w', encoding='utf-8') as html_file:
            html_file.write(html_str)
    else:
        return html_str


if __name__ == '__main__':
    print(init_all_resouce())
